package com.fast.develop.management.resource.compoment;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fast.develop.core.io.ResourceManager;
import com.fast.develop.management.resource.utils.SchemaFileUtil;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 莫寅
 * @createTime 2022-06-17 18:47
 * @desc：
 */
public class SchemaRemover {

    private ResourceManager resourceManager;

    public SchemaRemover(ResourceManager resourceManager) {
        this.resourceManager = resourceManager;
    }

    public void remove(String path){
        //是schema 节点删除
        if(SchemaFileUtil.isSchemaNodePath(path)){
            //获取文件路径
            String filePath = SchemaFileUtil.getFilePath(path);
            String schemaType = SchemaFileUtil.getSchemaType(path);
            String nodeName = SchemaFileUtil.getSchemaNodeName(path);

            //获取schema
            resourceManager.read(filePath);

            String fileValue = StrUtil.utf8Str(resourceManager.read(filePath));
            JSONObject jsonObject = JSONUtil.parseObj(fileValue);
            JSONArray jsonArray = jsonObject.getJSONArray(schemaType);
            //获取匹配节点
            AtomicReference<JSONObject> selectNodeObject = new AtomicReference<>();
            jsonArray.stream().forEach(o -> {
                JSONObject nodeObject = (JSONObject)o;
                if(nodeObject.getStr("name").equals(nodeName)){
                    selectNodeObject.set(nodeObject);
                }
            });

            if(selectNodeObject.get() != null){
                jsonArray.remove(selectNodeObject.get());
                //生成.json的文件，并写入数据
                resourceManager.createFile(filePath, JSONUtil.formatJsonStr(jsonObject.toString()).getBytes());
            }
        }
        //是否是文件
        else if(SchemaFileUtil.isFile(path)){
            resourceManager.remove(path);
        }
        //是文件夹
        else{
            resourceManager.remove(path);
        }



    }
}
